package com.levi.websocket;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArraySet;

/**
 * @author shentong
 * @since 2023/2/5 14:20
 */
@ServerEndpoint("/websocket/{userId}")
@Component
@Slf4j
public class WebSocketServer {


    private Session session;

    public static final CopyOnWriteArraySet<WebSocketServer> webSockets = new CopyOnWriteArraySet();

    private static final Map<String, Session> sessionPool = new ConcurrentHashMap();

    /**
     * 建立连接时候调用此方法
     * @param session
     * @param userId
     */
    @OnOpen
    public void onOpen(Session session, @PathParam("userId") String userId) {
        this.session = session;
        sessionPool.put(userId, session);
        webSockets.add(this);
        log.info("有新的链接，连接数是: {}",webSockets.size());
    }

    @OnMessage
    public void onMessage(String message) {
        log.info("收到客户端的消息: {}", message);
    }

    /**
     * 服务器向客户端发送消息
     * @param userId
     * @param message
     */
    public void sendMessage(String userId,String message) {
        Session session = sessionPool.get(userId);
        try {
            if (session != null && session.isOpen()) {
                log.info("webSocket服务器发送的消息:{}",message);
                session.getAsyncRemote().sendText(message);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
